package com.bj58.groupbuy.action.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.bj58.groupbuy.action.db.CommonDao;
import com.bj58.groupbuy.action.db.DBConfig;
import com.bj58.groupbuy.action.inter.CommonDataDeal;
import com.bj58.groupbuy.action.model.AllianceDataSourceReportVo;
import com.bj58.groupbuy.action.model.AllianceDataWirelessReportVo;
import com.bj58.groupbuy.action.service.EmailReportService;
import com.bj58.groupbuy.action.util.DateUtil;
public class EmailReportServiceImpl implements EmailReportService {
	private CommonDao comDao = new CommonDao();
	private CommonDataDeal comDeal = new CommonDataDeal();
	
	@Override
	public List<AllianceDataWirelessReportVo> adWLData(String nowDate,
			String lastDate, String lastWeek) {
		List<AllianceDataWirelessReportVo> finalList = new ArrayList<AllianceDataWirelessReportVo>();
		
		try {
			StringBuffer sql = new StringBuffer();
			List<String> cols = new ArrayList<String>();
			//渠道分收入数据
			sql.append(" SELECT statDate,concat(allianceName,advertType),sum(amount) FROM alliance_billing_metrics ");
			sql.append(" where cate1 = '无线'");
			sql.append(" and statDate in('"+nowDate+"','"+lastDate+"','"+lastWeek+"')  ");
			sql.append(" group by statDate,allianceName,advertType ");
			
			cols.add("statDate");cols.add("allianceName");cols.add("amountToday");
			List<AllianceDataWirelessReportVo> tempList = comDao.getCommonStatList(sql.toString(), cols, AllianceDataWirelessReportVo.class, DBConfig.db_68_ors.getIntType());
			
			//总计收入数据
			sql.delete(0, sql.length()+1);
			sql.append(" SELECT statDate,'总计',sum(amount) FROM `alliance_billing_metrics` ");
			sql.append(" where cate1 = '无线'");
			sql.append(" and statDate in('"+nowDate+"','"+lastDate+"','"+lastWeek+"')  ");
			sql.append(" group by statDate  ");
			List<AllianceDataWirelessReportVo> allTempList = comDao.getCommonStatList(sql.toString(), cols, AllianceDataWirelessReportVo.class, DBConfig.db_68_ors.getIntType());
			
			tempList.addAll(allTempList);
			
			TreeMap<String,List<AllianceDataWirelessReportVo>> tempMap = new TreeMap<String,List<AllianceDataWirelessReportVo>>();
			for(AllianceDataWirelessReportVo  vo : tempList){
				String key = vo.getAllianceName();
				List<AllianceDataWirelessReportVo> tList = new ArrayList<AllianceDataWirelessReportVo>();
				if(tempMap.containsKey(key)){
					tList = tempMap.get(key);
				}
				tList.add(vo);
				tempMap.put(key, tList);
			}
			
			for(Iterator<String> it = tempMap.keySet().iterator() ; it.hasNext();){
				String key = it.next();
				List<AllianceDataWirelessReportVo> tList =  tempMap.get(key);
				AllianceDataWirelessReportVo  addVo = new AllianceDataWirelessReportVo();
				addVo.setAllianceName(key);
				for(AllianceDataWirelessReportVo  vo : tList){
					String statDate = vo.getStatDate();
					if(nowDate.equals(statDate)){ 
						addVo.setAmountToday(vo.getAmountToday());
					}else if(lastDate.equals(statDate)){ 
						addVo.setAmountYesterDay(vo.getAmountToday());
					}else if(lastWeek.equals(statDate)){ 
						addVo.setAmountLastWeek(vo.getAmountToday());
					}
				}
				finalList.add(addVo);
			}
			
			//月累计和日均
			Date  sDate = DateUtil.strToDate(nowDate, "yyyy-MM-dd");
			String monthFirstDay = DateUtil.getFirstDay(sDate);	//当月第一天
			
			//总计 - 月累计
			cols.clear();
			cols.add("allianceName");cols.add("monthSum");
			
			sql.delete(0, sql.length()+1);
			sql.append(" SELECT '总计',sum(amount) FROM `alliance_billing_metrics`");
			sql.append(" where cate1 = '无线'");
			sql.append(" and statDate >= '"+monthFirstDay+"' ");
			sql.append(" and statDate <= '"+nowDate+"'");
			
			List<AllianceDataWirelessReportVo> monthAllTempList = comDao.getCommonStatList(sql.toString(), cols, AllianceDataWirelessReportVo.class, DBConfig.db_68_ors.getIntType());
			//分渠道月累计
			sql.delete(0, sql.length()+1);
			sql.append(" SELECT concat(allianceName,advertType),sum(amount) FROM `alliance_billing_metrics`");
			sql.append(" where cate1 = '无线'");
			sql.append(" and statDate >= '"+monthFirstDay+"' ");
			sql.append(" and statDate <= '"+nowDate+"'");
			sql.append(" group by allianceName,advertType");
				
			List<AllianceDataWirelessReportVo> monthTempList = comDao.getCommonStatList(sql.toString(), cols, AllianceDataWirelessReportVo.class, DBConfig.db_68_ors.getIntType());
			monthAllTempList.addAll(monthTempList);
			Map<String,AllianceDataWirelessReportVo> monthTempMap = new HashMap<String, AllianceDataWirelessReportVo>();
			for(AllianceDataWirelessReportVo vo : monthAllTempList){
				monthTempMap.put(vo.getAllianceName(), vo);
			}
			
			for(AllianceDataWirelessReportVo vo : finalList){
				String name = vo.getAllianceName();
				if(monthTempMap.containsKey(name)){
					AllianceDataWirelessReportVo monthVo = monthTempMap.get(name);
					//月累计
					vo.setMonthSum(monthVo.getMonthSum());
					//月均
					long subDay  = DateUtil.getDistDates(DateUtil.strToDate(monthFirstDay, "yyyy-MM-dd"), DateUtil.strToDate(nowDate, "yyyy-MM-dd")); //总天数
					double dayAvg = monthVo.getMonthSum()/(subDay+1);
					vo.setDayAvg(dayAvg);
				}
			}
			
			//将总计排在第一位
			List<AllianceDataWirelessReportVo> sList = new ArrayList<AllianceDataWirelessReportVo>();
			for(AllianceDataWirelessReportVo vo : finalList){
				String name = vo.getAllianceName();
				if("总计".equals(name)){
					sList.add(vo);
				}
			}
			if(!sList.isEmpty()){
				finalList.remove(sList.get(0));
				sList.addAll(finalList);
				finalList = sList;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return finalList;
	}

	@Override
	public List<AllianceDataSourceReportVo> adSourceData(List<String> dateList,
			int type) throws Exception {
		
		//sourcename - dic   infobright中文问题
		Map<String,String> sourceNameDicMap = new HashMap<String, String>();
		//查询条件Map
		Map<String,String> conditionMap = new HashMap<String, String>();
		if(type == 1){
			//精准CPC渠道收入
			sourceNameDicMap.put("cpcznall", "精准cpc站内总计");
			sourceNameDicMap.put("cpczwall", "精准cpc站外总计");
			
			conditionMap.put("cpcznall", " and source1 = '站内' ");
			conditionMap.put("cpczwall"," and source1 != '站内' ");
			
		}else if(type == 2){
			//精准CPC站外渠道收入  SQL需特殊处理
			sourceNameDicMap.put("zwdetail", "站外渠道明细");
		}else if(type == 3){
			//联盟重点合作方精准cpc收入
			sourceNameDicMap.put("momo", "陌陌");
			sourceNameDicMap.put("sq", "手机QQ");
			sourceNameDicMap.put("other58lm", "其他58联盟");
			
			conditionMap.put("momo", " and source2 = 'momo' ");
			conditionMap.put("sq", " and source2 = '手机QQ' ");
			conditionMap.put("other58lm"," and source1 = '58联盟' and source2 not in('momo','手机QQ') ");
		}
	
		Map<String,List<String>> sqlMap = new HashMap<String,List<String>>();
		
		List<String> cols = new ArrayList<String>();
		cols.add("statDate");
		cols.add("source");
		cols.add("amountToday");
		
		String today = dateList.get(0); //查询当日日期
		String monthFirstDay = DateUtil.getFirstDay(DateUtil.strToDate(today, "yyyy-MM-dd"));//当月第一天
		
		StringBuffer sql = new StringBuffer();
		dateList.add("all");  //月累加数据
		for(String searchDate : dateList){
			String month = "";
			if("all".equals(searchDate)){
				month = today.substring(0,today.lastIndexOf("-")).replace("-", "");
			}else{
				month = searchDate.substring(0,searchDate.lastIndexOf("-")).replace("-", "");
			}
			
			for(Iterator<String> it = sourceNameDicMap.keySet().iterator(); it.hasNext();){
				String sourceName  = it.next();

				sql.delete(0, sql.length()+1);
				sql.append(" select '" + searchDate +"',");
				if("zwdetail".equals(sourceName)){
					sql.append(" source1 ,");
				}else{
					sql.append("'" + sourceName+"',");
				}
				
				sql.append(" sum(cash)/100 ");
				sql.append(" from t_jingzhun_city_cate_stat_new_" + month);
				
				if("all".equals(searchDate)){
					sql.append(" where stat_date <= '"+ today +"'  and  stat_date>='" + monthFirstDay +"' ");
				}else{
					sql.append(" where stat_date = '"+ searchDate +"' ");
				}
				
				if("zwdetail".equals(sourceName)){
					sql.append(" and source1!='站内'  group by source1  ");
				}else{
					sql.append(conditionMap.get(sourceName));
				}
				
				sql.append(" :"+ DBConfig.db_94_data_app.getIntType());
				sqlMap.put(sql.toString(),cols);
			}
		}
		
		List<String> gbList = new ArrayList<String>();
		gbList.add("statDate");gbList.add("source");
		
		List<AllianceDataSourceReportVo> rsList = comDeal.AssembledDataBySqlMap(sqlMap, AllianceDataSourceReportVo.class, gbList);
	
		//按照source分组
		Map<String,List<AllianceDataSourceReportVo>> tempMap = new HashMap<String, List<AllianceDataSourceReportVo>>();
		for (AllianceDataSourceReportVo vo : rsList) {
			String source = vo.getSource();
			
			List<AllianceDataSourceReportVo> tempList = new ArrayList<AllianceDataSourceReportVo>();
			if(tempMap.containsKey(source)){
				tempList = tempMap.get(source);
			}
			
			tempList.add(vo);
			tempMap.put(source, tempList);
		}
		
		//数据融合
		List<AllianceDataSourceReportVo> finalList = new ArrayList<AllianceDataSourceReportVo>();
		for(Iterator<String> it = tempMap.keySet().iterator(); it.hasNext();){
			String source = it.next();
			
			AllianceDataSourceReportVo newVo = new AllianceDataSourceReportVo();
			newVo.setSource(source);
			
			List<AllianceDataSourceReportVo> tempList = tempMap.get(source);
			for (AllianceDataSourceReportVo vo : tempList) {
				String date = vo.getStatDate();
				if(dateList.get(0).equals(date)){  // 当日
					newVo.setAmountToday(vo.getAmountToday());
				}else if(dateList.get(1).equals(date)){  // 昨日
					newVo.setAmountYesterDay(vo.getAmountToday());
				}else if(dateList.get(2).equals(date)){  // 上周
					newVo.setAmountLastWeek(vo.getAmountToday());
				}else if(dateList.get(3).equals(date)){  //  月汇总
					newVo.setMonthSum(vo.getAmountToday());
				}
			}
			
			//日均
			long subDay  = DateUtil.getDistDates(DateUtil.strToDate(monthFirstDay, "yyyy-MM-dd"), DateUtil.strToDate(today, "yyyy-MM-dd")); //总天数
			double dayAvg = newVo.getMonthSum()/(subDay+1);
			newVo.setDayAvg(dayAvg);
			
			finalList.add(newVo);
		}
		
		
		//翻译sourceName
		if(type != 2){
			for (AllianceDataSourceReportVo vo : finalList) {
				vo.setSource(sourceNameDicMap.get(vo.getSource()));
			}
		}
		
		//精准CPC渠道收入表  需要将站内站外的总计数据统计出来
		if(type == 1){
			AllianceDataSourceReportVo allVo = new AllianceDataSourceReportVo();
			allVo.setSource("精准cpc总计");
			
			for (AllianceDataSourceReportVo vo : finalList) {
				allVo.setAmountToday(allVo.getAmountToday() + vo.getAmountToday());
				allVo.setAmountYesterDay(allVo.getAmountYesterDay() + vo.getAmountYesterDay());
				allVo.setAmountLastWeek(allVo.getAmountLastWeek() + vo.getAmountLastWeek());
				allVo.setMonthSum(allVo.getMonthSum() + vo.getMonthSum());
				allVo.setDayAvg(allVo.getDayAvg() + vo.getDayAvg());
			}
			//总计放在第一位
			finalList.add(0, allVo);
		}
		return finalList;
	}
	
	
}

